package service

import (
	"backend_api/internal/global"
	"backend_api/internal/model"
	"backend_api/internal/model/request"
)

type WebsiteSettingService struct{}

func (s *WebsiteSettingService) GetSetting() (*model.WebsiteSetting, error) {
	var setting model.WebsiteSetting
	result := global.DB.Select("id, site_name, copyright, icp_record, index_title, index_keywords, index_desc, created_at, updated_at").Order("id desc").First(&setting)
	return &setting, result.Error
}

func (s *WebsiteSettingService) UpdateSetting(req *request.WebsiteSettingUpdate) error {
	setting := &model.WebsiteSetting{
		SiteName:      req.SiteName,
		Copyright:     req.Copyright,
		IcpRecord:     req.IcpRecord,
		IndexTitle:    req.IndexTitle,
		IndexKeywords: req.IndexKeywords,
		IndexDesc:     req.IndexDesc,
	}

	var count int64
	global.DB.Model(&model.WebsiteSetting{}).Count(&count)

	if count == 0 {
		return global.DB.Create(setting).Error
	}
	getData, _ := s.GetSetting()
	return global.DB.Model(&model.WebsiteSetting{}).Where("id = ?", getData.ID).Updates(setting).Error
}
